// 加载Express模块
const express = require('express');

// 加载MySQL模块
const mysql = require('mysql');

// 加载bodyParser模块
const bodyParser = require('body-parser');

// 加载MD5模块
const md5 = require('md5');

// 创建MySQL连接池
const pool = mysql.createPool({
  host: '127.0.0.1',   //MySQL服务器地址
  port: 3306,          //MySQL服务器端口号
  user: 'root',        //数据库用户的用户名
  password: '',        //数据库用户密码
  database: 'wumu',    //数据库名称
  connectionLimit: 20, //最大连接数
  charset: 'utf8'      //数据库服务器的编码方式
});



// 创建服务器对象
const server = express();

server.use(bodyParser.urlencoded({
  extended: false
}));

// 指定服务器对象监听的端口号
server.listen(3000, () => {
  console.log('server is running...');
});

// 加载CORS模块
const cors = require('cors');

// 使用CORS中间件
server.use(cors({
  origin: ['http://localhost:8080', 'http://127.0.0.1:8080']
}));

// 获取欧式甜点的接口
server.get('/edessert', (req, res) => {
  // SQL语句以获取欧式甜点表的数据
  let sql = 'SELECT * FROM cake_E ';
  // 执行SQL语句
  pool.query(sql, (error, results) => {
    if (error) throw error;
    res.send({ message: 'ok', code: 200, results: results });
  });
});


// 获取日式甜点的接口
server.get('/jdessert', (req, res) => {
  // SQL语句以获取日式甜点表的数据
  let sql = 'SELECT * FROM cake_J ';
  // 执行SQL语句
  pool.query(sql, (error, results) => {
    if (error) throw error;
    res.send({ message: 'ok', code: 200, results: results });
  });
});


// 获取中式甜点的接口
server.get('/cdessert', (req, res) => {
  // SQL语句以获取日式甜点表的数据
  let sql = 'SELECT * FROM cake_C ';
  // 执行SQL语句
  pool.query(sql, (error, results) => {
    if (error) throw error;
    res.send({ message: 'ok', code: 200, results: results });
  });
});


// 获取韩式甜点的接口
server.get('/kdessert', (req, res) => {
  // SQL语句以获取日式甜点表的数据
  let sql = 'SELECT * FROM cake_K ';
  // 执行SQL语句
  pool.query(sql, (error, results) => {
    if (error) throw error;
    res.send({ message: 'ok', code: 200, results: results });
  });
});


// 获取特别推荐的接口
server.get('/sdessert', (req, res) => {
  // SQL语句以获取日式甜点表的数据
  let sql = 'SELECT * FROM cake_S ';
  // 执行SQL语句
  pool.query(sql, (error, results) => {
    if (error) throw error;
    res.send({ message: 'ok', code: 200, results: results });
  });
});


//用户预订接口
server.post('/preserve', (req, res) => {
  // 获取用户名、电话号码、用餐人数、预订时间信息
  let uname = req.body.uname;
  let uphone = req.body.uphone;
  let unumber = req.body.unumber;
  let utime = req.body.utime;
  //以uphone为条件进行查找操作，以保证用户名的唯一性
  let sql = 'SELECT COUNT(id) AS count FROM .... WHERE uphone=?';
  pool.query(sql, [uphone], (error, results) => {
    if (error) throw error;
    let count = results[0].count;
    if (count == 0) {
      // 将用户的相关信息插入到数据表
      sql = 'INSERT wumu_user(uname,uphone,unumber,utime) VALUES(?,?,?,?)';
      pool.query(sql,(error, results) => {
        if (error) throw error;
        res.send({ message: 'ok', code: 200 });
      })
    } else {
      res.send({ message: 'user exists', code: 201 });
    }
  });
});



